package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Member;
import com.itheima.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class MemberServiceImpl implements MemberService {

    @Autowired
    MemberDao memberDao;

    //根据手机号查询会员
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }


    //新增会员
    public void add(Member member) {
        memberDao.add(member);
    }

    @Override
    public Map<String, Object> getMemberReport() {
        List<String> months = getMonthOfLastYear();
        List<Long> memberCount = new ArrayList<>();
        //统计每个月份对应的会员数量
        for (String month : months) {
            String firstDay = month + "-01"; // 2020-01-01
            String lastDay = getThisMonthLastDay(firstDay);
            long count = memberDao.findCountBeforeByDate(lastDay);
            memberCount.add(count);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCount);
        return map;
    }

    @Override
    public Map<String, Object> findMemberReport(List<String> dateStr){
        log.debug("findMemberReport dateStr:" + dateStr);
        String firstDate = dateStr.get(0);
        String lastDate = dateStr.get(1);
        int days = 0;
        try {
            days = daysBetween(firstDate, lastDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        log.debug("相差天数:" + days);
        if (days >=30) {
            return  getMonthdate(firstDate, lastDate);
        } else{
            return getDaydate(firstDate, lastDate);
        }
    }

    /**
     * 按天查询会员
     * @param firstDate
     * @param lastDate
     * @return
     */
    public Map<String, Object> getDaydate(String firstDate, String lastDate) {
        List<String> months= memberDao.getMonthBetween(firstDate, lastDate);
        ArrayList<Long> memCount = new ArrayList<>();
        if (months ==null ||months.size()<=0) {
            throw new BusinessRuntimeException("无该时间段数据");
        }
        Collections.sort(months);
        for (String month : months) {
            long count = memberDao.findCountBeforeByDate(month);
            memCount.add(count);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memCount);
        return map;
    }

    /**
     * 按月查询会员
     * @param firstDate
     * @param lastDate
     * @return
     */
    public Map<String, Object> getMonthdate(String firstDate, String lastDate) {
        ArrayList<Long> memCount = new ArrayList<>();
        ArrayList<String> months = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List<String> monthList= memberDao.getMonthBetween(firstDate, lastDate);
        if (monthList ==null ||monthList.size()<=0) {
            throw new BusinessRuntimeException("无该时间段数据");
        }
        Collections.sort(monthList);
        for (String mont : monthList) {
            try {
                String format= sdf.format(sdf.parse(mont));
                months.add(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        log.debug("monthList: " + monthList);

        for (int i = 0; i < months.size() - 1; i++) {
            // 从list中索引为 list.size()-1 开始往前遍历
            for (int j = months.size() - 1; j > i; j--) {
                // 进行比较
                if (months.get(j).equals(months.get(i))) {
                    // 去重
                    months.remove(j);
                }
            }
        }
        for (String month : months) {
            String firstDay = month + "-01"; // 2020-01-01
            String lastDay = getThisMonthLastDay(firstDay);
            long count = memberDao.findCountBeforeByDate(lastDay);
            memCount.add(count);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memCount);
        return map;
    }



    /**
     * 获取两个日期相差天数
     * @param smdate
     * @param bdate
     * @return
     */
    public static int daysBetween(String smdate,String bdate) throws ParseException{
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();

        cal.setTime(sdf.parse(smdate));

        long time1 = cal.getTimeInMillis();

        cal.setTime(sdf.parse(bdate));

        long time2 = cal.getTimeInMillis();

        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));

    }


    /**
     * 根据这个月第一天获取这个月最后一天
     */
    private String getThisMonthLastDay(String firstDay) {
        //2020-02-01 thisMonthFirstDay
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date firstDate = sdf.parse(firstDay);
            //创建日历对象
            Calendar cal = Calendar.getInstance();
            //设置为本月一号
            cal.setTime(firstDate);
            //调整为下月1号
            cal.add(Calendar.MONTH, 1);
            //调整为前一天(本月的最后一天)
            cal.add(Calendar.DAY_OF_MONTH, -1);
            String str = sdf.format(cal.getTime());
            return str;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取最近一年的月份
     * * @return
     */
    private List<String> getMonthOfLastYear() {
        List<String> months = new ArrayList<>();
        //获取前12个月份
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
            String date = simpleDateFormat.format(calendar.getTime());
            months.add(date);
        }
        return months;
    }


}
